package session.stateless.CRM;

import entity.CRM.Customer;
import entity.CRM.LineItem;
import entity.CRM.ProductPrice;
import entity.CRM.SaleInquiry;
import entity.CRM.SaleLead;
import entity.CRM.SaleQuotation;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SaleInquiryBean implements SaleInquiryBeanLocal {
    @PersistenceContext()
    EntityManager em;
    
    @EJB
    private DiscountBeanLocal discountBeanLocal;    
    @EJB
    private SaleLeadBeanLocal saleLeadBeanLocal;
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    NumberFormat formatter = new DecimalFormat("#0.00");
    
    public Double calculateFinalPrice(ProductPrice productPrice, Long quantity, Double customDiscount) {
        Double temp_VolumeDiscountRate =discountBeanLocal.calculateDiscountRate(productPrice.getProductType(), quantity);
        Double temp_FinalPrice =productPrice.getProductPrice()*quantity* (1-(temp_VolumeDiscountRate+customDiscount)/100);
        return temp_FinalPrice;
    }
    
    public LineItem createLineItem_CustomDiscountIncluded(ProductPrice productPrice, Long quantity, Double customDiscount) {
        LineItem lineItem = new LineItem();
        
        lineItem.setLineItemQuantity(quantity);
        lineItem.setProductPrice(productPrice);
        
        Double finalPrice = productPrice.getProductPrice()*quantity*(1-customDiscount/100);
        lineItem.setFinalPrice(new Double(formatter.format(finalPrice)));
        lineItem.setVolumeDiscountRate(discountBeanLocal.calculateDiscountRate(productPrice.getProductType(), quantity));
        
        em.persist(lineItem);
        em.flush();
        
        return lineItem;        
    }
    public LineItem createLineItem_VolumeDiscountIncluded(ProductPrice productPrice, Long quantity)
    {
        LineItem lineItem = new LineItem();
        lineItem.setLineItemQuantity(quantity);
        lineItem.setProductPrice(productPrice);
        
        Double discountRate=discountBeanLocal.calculateDiscountRate(productPrice.getProductType(), quantity);
        lineItem.setVolumeDiscountRate(discountRate);
        Double finalPrice =productPrice.getProductPrice()*quantity* (1-discountRate/100);
        lineItem.setFinalPrice(new Double(formatter.format(finalPrice)));
        
        em.persist(lineItem);
        em.flush();
        
        return lineItem;            
    }
    public LineItem createLineItem_VolumeCustomDiscountIncluded(ProductPrice productPrice, Long quantity, Double customDiscount) {
        LineItem lineItem = new LineItem();
        
        lineItem.setLineItemQuantity(quantity);
        lineItem.setProductPrice(productPrice);
        
        Double discountRate=discountBeanLocal.calculateDiscountRate(productPrice.getProductType(), quantity);
        lineItem.setVolumeDiscountRate(discountRate);
        Double finalPrice =productPrice.getProductPrice()*quantity* (1-(discountRate+customDiscount)/100);
        lineItem.setFinalPrice(new Double(formatter.format(finalPrice)));
        
        em.persist(lineItem);
        em.flush();
        
        return lineItem;
        
    }
    
    public void deleteLineItem(long lineItemId){
        LineItem lineItem = em.find(LineItem.class, lineItemId);
        if(lineItem==null){
            System.out.println("Line Item does not exist!");
        }
        else{
            lineItem.setProductPrice(null);
            em.remove(lineItem);
            em.flush();
        }
    }
   
    public Long createSaleInquiry(String saleLeadName,List<LineItem> lineItems, Double customDiscount) {
        SaleInquiry saleInquiry = new SaleInquiry();
        SaleLead saleLead =saleLeadBeanLocal.findByName(saleLeadName);
        
        if (saleLead == null)
        {
            return null;
        }
        else
        {
            saleInquiry.setSaleLead(saleLead);               
            
            saleInquiry.setLineItems(lineItems);
            Date date = new Date();
            saleInquiry.setSaleInquiryDate(dateFormat.format(date));
            saleInquiry.setCustomDiscount(customDiscount);
            
            em.persist(saleInquiry);
            em.flush();
            saleLead.getSaleInquiries().add(saleInquiry);
            em.flush();
            
            return saleInquiry.getId();
        }
    }

    public void updateSaleInquiry(Long saleInquiryId, List<LineItem> lineItems) {
        SaleInquiry saleInquiry =em.find(SaleInquiry.class, saleInquiryId);
        
        if (saleInquiry ==null)
        {
            System.out.println("Sale Inquiry does not exist.");            
        }
        else
        {
            Object[] objectList = saleInquiry.getLineItems().toArray();
            saleInquiry.setLineItems(null);
            ArrayList<LineItem> tempLineItems = new ArrayList<LineItem>();
            LineItem lineItem = new LineItem();
            for(int i=0; i<objectList.length;i++){
                lineItem = (LineItem) objectList[i];
                deleteLineItem(lineItem.getLineItemId());
            }
            
            
            objectList = lineItems.toArray();
            for(int i=0; i<objectList.length;i++){
                lineItem = (LineItem) objectList[i];
                tempLineItems.add(createLineItem_VolumeCustomDiscountIncluded(lineItem.getProductPrice(), lineItem.getLineItemQuantity(), saleInquiry.getCustomDiscount()));
            }
            
            saleInquiry.setLineItems(tempLineItems);
            em.persist(saleInquiry);
            em.flush();
        }
    }
    public void deleteSaleInquiry(Long saleInquiryId) {
        SaleInquiry saleInquiry = em.find(SaleInquiry.class, saleInquiryId);
        
        if (saleInquiry ==null)
        {
            System.out.println("Sale Inquiry does not exist");
        }
        else
        {
            List<SaleInquiry> newSaleInquiries = new ArrayList<SaleInquiry>();
            newSaleInquiries = saleInquiry.getSaleLead().getSaleInquiries();
            newSaleInquiries.remove(saleInquiry);
            
            saleInquiry.getSaleLead().setSaleInquiries(newSaleInquiries);
            
            Object[] objectList = saleInquiry.getLineItems().toArray();
            saleInquiry.setLineItems(null);
            LineItem lineItem = new LineItem();
            for(int i=0; i<objectList.length;i++){
                lineItem = (LineItem) objectList[i];
                deleteLineItem(lineItem.getLineItemId());
            }
            
            em.remove(saleInquiry);
            em.flush();
        }
    }

    public List<SaleInquiry> getSaleInquiries() {
        Query q1=em.createQuery("SELECT c FROM SaleInquiry c");
        List<SaleInquiry> saleInquiryList = q1.getResultList();
        
        Query q2 = em.createQuery("SELECT c FROM SaleQuotation c");
        List<SaleQuotation> saleQuotationList = q2.getResultList();
        
        for(Object o: saleQuotationList){
            SaleInquiry temp = (SaleInquiry) o;
            saleInquiryList.remove(temp);
        }
        
        return saleInquiryList;
    }
    public List<SaleInquiry> getSaleInquiriesBySaleLead(String registrationNumber) {
        SaleLead saleLead=em.find(SaleLead.class, registrationNumber);
        
        return (List<SaleInquiry>) saleLead.getSaleInquiries();
    }
    public List<SaleInquiry> getSaleInquiriesByCustomer(String registrationNumber) {
        Customer customer =em.find(Customer.class, registrationNumber);
        
        return customer.getSaleInquiries();
    }
    
    public List<ProductPrice> getProductPrice() {
        Query q = em.createQuery("SELECT c FROM ProductPrice c");
        
        return q.getResultList();
    }

    public List<String> getProductPriceTypes()
    {
        Query q = em.createQuery("SELECT c FROM ProductPrice c");
        List<ProductPrice> productPrices = q.getResultList();
        List<String> productTypes = new ArrayList<String>();
        for (ProductPrice productPrice:productPrices)
        {
            if (!productTypes.contains(productPrice.getProductType()))
                productTypes.add(productPrice.getProductType());
        }
        return productTypes;
    }

    
}
